'balance' is a Python package that is maintained and released by the Core Data Science Tel-Aviv team in Meta. 'balance' performs and evaluates bias reduction by weighting for a broad set of experimental and observational use cases.
Although balance is written in Python, you don't need a deep Python understanding to use it. In fact, you can just use this notebook, load your data, change some variables and re-run the notebook and produce your own weights!
This quickstart demonstrates re-weighting specific simulated data, but if you have a different usecase or want more comprehensive documentation, you can check out the comprehensive balance tutorial.
There are four main steps to analysis with balance:
Let's dive right in!
The following is a toy simulated dataset.
import warnings
warnings.filterwarnings("ignore")
from balance import load_data
INFO (2023-02-01 18:17:57,248) [__init__/<module> (line 52)]: Using balance version 0.3.0
target_df, sample_df = load_data()
print("target_df: \n", target_df.head())
print("sample_df: \n", sample_df.head())
target_df:
id gender age_group income
0 100000 Male 45+ 10.183951
1 100001 Male 45+ 6.036858
2 100002 Male 35-44 5.226629
3 100003 NaN 45+ 5.752147
4 100004 NaN 25-34 4.837484
sample_df:
id gender age_group income happiness
0 0 Female 25-34 1.038463 55.975764
1 1 Male 45+ 0.214603 58.645154
2 2 Male 35-44 2.322137 42.285653
3 3 NaN 18-24 0.086068 49.210985
4 4 NaN 35-44 17.156958 49.330845
target_df.head().round(2).to_dict()
# sample_df.shape
{'id': {0: '100000', 1: '100001', 2: '100002', 3: '100003', 4: '100004'},
'gender': {0: 'Male', 1: 'Male', 2: 'Male', 3: nan, 4: nan},
'age_group': {0: '45+', 1: '45+', 2: '35-44', 3: '45+', 4: '25-34'},
'income': {0: 10.18, 1: 6.04, 2: 5.23, 3: 5.75, 4: 4.84}}
In practice, one can use pandas loading function(such as read_csv()) to import data into the DataFrame objects sample_df and target_df.
The first thing to do is to import the Sample class from balance. All of the data we're going to be working with, sample or population, will be stored in objects of the Sample class.
from balance import Sample
Using the Sample class, we can fill it with a "sample" we want to adjust, and also a "target" we want to adjust towards.
We turn the two input pandas DataFrame objects we created (or loaded) into a balance.Sample objects, by using the .from_frame()
sample = Sample.from_frame(sample_df, outcome_columns=["happiness"])
target = Sample.from_frame(target_df)
WARNING (2023-02-01 18:17:57,477) [util/guess_id_column (line 111)]: Guessed id column name id for the data WARNING (2023-02-01 18:17:57,482) [sample_class/from_frame (line 225)]: No weights passed, setting all weights to 1 WARNING (2023-02-01 18:17:57,492) [util/guess_id_column (line 111)]: Guessed id column name id for the data WARNING (2023-02-01 18:17:57,503) [sample_class/from_frame (line 225)]: No weights passed, setting all weights to 1
If we use the .df property call, we can see the DataFrame stored in sample. We can see how we have a new weight column that was added (it will all have 1s) in the importing of the DataFrames into a balance.Sample object.
sample.df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 1000 entries, 0 to 999 Data columns (total 6 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 1000 non-null object 1 gender 912 non-null object 2 age_group 1000 non-null object 3 income 1000 non-null float64 4 happiness 1000 non-null float64 5 weight 1000 non-null int64 dtypes: float64(2), int64(1), object(3) memory usage: 47.0+ KB
We can get a quick overview text of each Sample object, but just calling it.
Let's take a look at what this produces:
sample
(balance.sample_class.Sample)
balance Sample object
1000 observations x 3 variables: gender,age_group,income
id_column: id, weight_column: weight,
outcome_columns: happiness
target
(balance.sample_class.Sample)
balance Sample object
10000 observations x 3 variables: gender,age_group,income
id_column: id, weight_column: weight,
outcome_columns: None
Next, we combine the sample object with the target object. This is what will allow us to adjust the sample to the target.
sample_with_target = sample.set_target(target)
Looking on sample_with_target now, it has the target atteched:
sample_with_target
(balance.sample_class.Sample)
balance Sample object with target set
1000 observations x 3 variables: gender,age_group,income
id_column: id, weight_column: weight,
outcome_columns: happiness
target:
balance Sample object
10000 observations x 3 variables: gender,age_group,income
id_column: id, weight_column: weight,
outcome_columns: None
3 common variables: income,age_group,gender
We can use .covars() and then followup with .mean() and .plot() (barplots and qqplots) to get some basic diagnostics on what we got.
We can see how:
print(sample_with_target.covars().mean().T)
source self target _is_na_gender[T.True] 0.08800 0.089800 age_group[T.25-34] 0.30900 0.297400 age_group[T.35-44] 0.17200 0.299200 age_group[T.45+] 0.04600 0.206300 gender[Female] 0.26800 0.455100 gender[Male] 0.64400 0.455100 gender[_NA] 0.08800 0.089800 income 5.99102 12.737608
print(sample_with_target.covars().asmd().T)
source self age_group[T.25-34] 0.025375 age_group[T.35-44] 0.277771 age_group[T.45+] 0.396127 gender[Female] 0.375699 gender[Male] 0.379314 gender[_NA] 0.006296 income 0.517721 mean(asmd) 0.334860
print(sample_with_target.covars().asmd(aggregate_by_main_covar = True).T)
source self age_group 0.233091 gender 0.253769 income 0.517721 mean(asmd) 0.334860
sample_with_target.covars().plot()
Next, we adjust the sample to the target. The default method to be used is 'ipw' (which uses inverse probability/propensity weights, after running logistic regression with lasso regularization).
# Using ipw to fit survey weights
adjusted = sample_with_target.adjust(max_de=None)
INFO (2023-02-01 18:17:58,239) [ipw/ipw (line 428)]: Starting ipw function INFO (2023-02-01 18:17:58,242) [adjustment/apply_transformations (line 255)]: Adding the variables: [] INFO (2023-02-01 18:17:58,242) [adjustment/apply_transformations (line 256)]: Transforming the variables: ['income', 'age_group', 'gender'] INFO (2023-02-01 18:17:58,253) [adjustment/apply_transformations (line 293)]: Final variables in output: ['income', 'age_group', 'gender'] INFO (2023-02-01 18:17:58,262) [ipw/ipw (line 462)]: Building model matrix INFO (2023-02-01 18:17:58,356) [ipw/ipw (line 486)]: The formula used to build the model matrix: ['income + gender + age_group + _is_na_gender'] INFO (2023-02-01 18:17:58,357) [ipw/ipw (line 489)]: The number of columns in the model matrix: 16 INFO (2023-02-01 18:17:58,358) [ipw/ipw (line 490)]: The number of rows in the model matrix: 11000 INFO (2023-02-01 18:17:58,367) [ipw/ipw (line 521)]: Fitting logistic model INFO (2023-02-01 18:18:00,131) [ipw/ipw (line 593)]: Chosen lambda for cv: [0.01386604] INFO (2023-02-01 18:18:00,133) [ipw/ipw (line 601)]: Proportion null deviance explained [0.17374302]
print(adjusted)
Adjusted balance Sample object with target set using ipw
1000 observations x 3 variables: gender,age_group,income
id_column: id, weight_column: weight,
outcome_columns: happiness
target:
balance Sample object
10000 observations x 3 variables: gender,age_group,income
id_column: id, weight_column: weight,
outcome_columns: None
3 common variables: income,age_group,gender
We can get a basic summary of the results:
print(adjusted.summary())
Covar ASMD reduction: 62.3%, design effect: 2.249 Covar ASMD (7 variables): 0.335 -> 0.126 Model performance: Model proportion deviance explained: 0.174
print(adjusted.covars().mean().T)
source self target unadjusted _is_na_gender[T.True] 0.103449 0.089800 0.08800 age_group[T.25-34] 0.279072 0.297400 0.30900 age_group[T.35-44] 0.290137 0.299200 0.17200 age_group[T.45+] 0.150714 0.206300 0.04600 gender[Female] 0.410664 0.455100 0.26800 gender[Male] 0.485887 0.455100 0.64400 gender[_NA] 0.103449 0.089800 0.08800 income 9.519935 12.737608 5.99102
We see an improvement in the average ASMD. We can look at detailed list of ASMD values per variables using the following call.
print(adjusted.covars().asmd().T)
source self unadjusted unadjusted - self age_group[T.25-34] 0.040094 0.025375 -0.014719 age_group[T.35-44] 0.019792 0.277771 0.257980 age_group[T.45+] 0.137361 0.396127 0.258765 gender[Female] 0.089228 0.375699 0.286472 gender[Male] 0.061820 0.379314 0.317494 gender[_NA] 0.047739 0.006296 -0.041444 income 0.246918 0.517721 0.270802 mean(asmd) 0.126310 0.334860 0.208551
It's easier to learn about the biases by just running .covars().plot() on our adjusted object.
adjusted.covars().plot()
We can also use different plots, using the seaborn library, for example with the "kde" dist_type.
# This shows how we could use seaborn to plot a kernel density estimation
adjusted.covars().plot(library = "seaborn", dist_type = "kde")
We can look at the distribution of weights using the following call.
adjusted.weights().plot()
And get the design effect using:
adjusted.weights().design_effect()
2.24937899455838
print(adjusted.outcomes().summary())
WARNING (2023-02-01 18:18:01,920) [balancedf_class/target_response_rates (line 1307)]: Sample does not have target set
1 outcomes: ['happiness']
Mean outcomes:
happiness
source
self 54.221388
unadjusted 48.392784
Response rates (relative to number of respondents in sample):
happiness
n 1000.0
% 100.0
The estimated mean happiness according to our sample is 48 without any adjustment and 54 with adjustment. The following show the distribution of happinnes:
adjusted.outcomes().plot()
Finally, we can prepare the data to be downloaded for future analyses.
adjusted.to_download()
# We can prepare the data to be exported as csv - showing the first 500 charaacters for simplicity:
adjusted.to_csv()[0:500]
'id,gender,age_group,income,happiness,weight\n0,Female,25-34,1.0384632065106263,55.9757637459091,10.388001723788236\n1,Male,45+,0.21460348629627557,58.645154141877306,21.221032388150093\n2,Male,35-44,2.3221372597327745,42.28565260361035,9.106922937954346\n3,,18-24,0.08606802599581903,49.21098472260077,5.439376521985937\n4,,35-44,17.156958197550072,49.33084508361814,31.000269201720744\n5,,35-44,4.257130738748466,67.46904416515795,19.23721007589055\n6,,25-34,1.0092927734150772,40.03387164850365,9.24657776'
# Sessions info
import session_info
session_info.show(html=False, dependencies=True)
----- balance 0.3.0 pandas 1.4.3 session_info 1.0.0 ----- PIL 9.4.0 apport_python_hook NA argcomplete NA asttokens NA attr 21.2.0 backcall 0.2.0 cffi 1.15.1 colorama 0.4.4 comm 0.1.2 coxnet NA cvcompute NA cvelnet NA cvfishnet NA cvglmnet NA cvglmnetCoef NA cvglmnetPredict NA cvlognet NA cvmrelnet NA cvmultnet NA cycler 0.10.0 cython_runtime NA dateutil 2.8.2 debugpy 1.6.6 decorator 5.1.1 defusedxml 0.7.1 elnet NA executing 1.2.0 fastjsonschema NA fishnet NA glmnet NA glmnetCoef NA glmnetControl NA glmnetPredict NA glmnetSet NA glmnet_python NA idna 3.3 ipykernel 6.20.2 ipython_genutils 0.2.0 jedi 0.18.2 joblib 1.2.0 jsonpointer 2.0 jsonschema 3.2.0 kiwisolver 1.4.4 loadGlmLib NA lognet NA matplotlib 3.6.3 matplotlib_inline 0.1.6 mpl_toolkits NA mrelnet NA nbformat 5.7.3 netifaces 0.11.0 numpy 1.24.1 packaging 23.0 parso 0.8.3 patsy 0.5.3 pexpect 4.8.0 pickleshare 0.7.5 pkg_resources NA platformdirs 2.6.2 plotly 5.13.0 prompt_toolkit 3.0.36 psutil 5.9.4 ptyprocess 0.7.0 pure_eval 0.2.2 pvectorc NA pydev_ipython NA pydevconsole NA pydevd 2.9.5 pydevd_file_utils NA pydevd_plugins NA pydevd_tracing NA pygments 2.14.0 pyparsing 2.4.7 pyrsistent NA pytz 2022.1 rfc3339_validator 0.1.4 rfc3986_validator 0.1.1 scipy 1.9.2 seaborn 0.11.1 sitecustomize NA six 1.16.0 sklearn 1.2.1 sphinxcontrib NA stack_data 0.6.2 statsmodels 0.13.5 tenacity NA threadpoolctl 3.1.0 tornado 6.2 traitlets 5.9.0 typing_extensions NA wcwidth 0.2.6 wtmean NA zmq 25.0.0 zope NA ----- IPython 8.9.0 jupyter_client 8.0.2 jupyter_core 5.2.0 notebook 6.5.2 ----- Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] Linux-5.15.0-1031-azure-x86_64-with-glibc2.35 ----- Session information updated at 2023-02-01 18:18